import axios from "axios";
import { ElMessage } from "element-plus";
import { LS } from "@/utils/common";
const request = axios.create({
  baseURL: import.meta.env.DEV ? 'http://121.89.205.189:3000/admin' : 'http://121.89.205.189:3000/admin',
  timeout: 5000,
})
export const requestMock = axios.create({
  baseURL: 'http:1.1.1.1',
  timeout: 5000,
})

// 请求头
let requestCount = 0;
([request, requestMock]).forEach(item => {
  item.interceptors.request.use((config) => {
    requestCount++
    const token = LS.get('admininfo')?.token
    config.headers.token = token
    return config
  }, (error) => {
    return Promise.reject(error)
  })
});


// 响应拦截器
([request, requestMock]).forEach(item => {
  item.interceptors.response.use((response) => {
    requestCount--
    const { full = false, silence = false, loud = false, method } = response.config
    if ((method === 'get' && loud) || (method !== 'get' && !silence)) {
      if (response.data.code === '200' || response.data.status === 1) {
        ElMessage({ type: 'success', message: response.data.message, duration: 1500 })
      } else {
        ElMessage({ type: 'danger', message: response.data.message, duration: 1500 })

      }
    }
    if (response.data.code === '10119') { }
    if (response.data.code === '200' || response.data.code === 1) {
      return full ? response.data : response.data.data
    }
    throw new Error(response.data.message || '未知错误')
  }, (error) => {
    return Promise.reject(error)
  })
})

export default request